<template>
    <statusBar bgc="transparent" />
    <view class="page">
        <view class="topBox">
            <userHeader :time="new Date().getTime()" />
        </view>

        <view class="target" v-if="userRole != 0 && userRole != 4 && groupNum != 0">
            <image src="/static/home/groupTarget.png"></image>
            <view class="text">您的团队还差{{ groupNum }}人，即可达成金牌{{ userRoleType[userInfomation?.identityType] }}称号</view>
        </view>

        <view class="dataBoard">
            <view class="item" v-for="(item, index) in userDataBoardText[userRole]" :key="index" @click="dataBoardItemClick(index + 1)">
                <view class="value">
                    {{ TodayIncome[index] || 0 }}
                </view>
                <view class="label">
                    {{ item }}
                </view>
            </view>
        </view>

        <view class="agencyFeeRemind" v-if="userRole != 0 && userRole != 4 && unpaidAgencyFees != 0" @click="goAgencyFeePay">
            <!-- <span>请补齐代理费用{{ unpaidAgencyFees }}元，方可进行提现</span> -->
            <span>点击缴纳代理费</span>

            <image src="/static/home/icon_more_blue.png"></image>
        </view>

        <view class="cards">
            <view class="card" v-for="item in userCards" @click="cardClick(item)" :key="item.title">
                <view class="title">
                    {{ item.title }}
                </view>
                <view class="desc">
                    {{ item.desc }}
                </view>
                <image src="/static/home/icon_more_blue.png"></image>

                <image class="icon" :src="item.icon"></image>
            </view>
        </view>

        <view class="charts">
            <view class="item">
                <view class="title">
                    {{ userRole !== 0 ? '订单收入趋势' : '新增人数趋势' }}
                    <span>近七天</span>
                </view>

                <view class="charts-box">
                    <qiunDataCharts type="column" :opts="opts" :chartData="chartsData1" />
                </view>
            </view>
            <view class="item">
                <view class="title">
                    {{ userRole !== 0 ? '提成收入趋势' : '推广收益趋势' }}
                    <span>近七天</span>
                </view>

                <view class="charts-box">
                    <qiunDataCharts type="column" :opts="opts" :chartData="chartsData2" />
                </view>
            </view>
        </view>
    </view>

    <uni-popup ref="progressPopup" type="center" mask-background-color="rgba(0,0,0,0)" :is-mask-click="false">
        <view class="progressPopupContent">
            <view class="title">下载进度</view>
            <view class="progressBox">
                <view class="progress"></view>
                <view class="progress_a" :style="{ width: downloadProgress + '%' }"></view>

                <view class="progress_text">下载进度：{{ downloadProgress }}%</view>
            </view>
        </view>
    </uni-popup>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import qiunDataCharts from '@/uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue';
import { commonApis, getUserInfoMethod, homeApis, userApis } from '@/utils/apis';

const userRole = ref(0); //0推广 1管家   2 运营中心
const userRoleType = ['悦居推客', '悦居管家', '运营中心', '市级代理', '省级代理'];

//echarts图表数据
const opts = {
    color: ['#2C72FF'],
    padding: [15, 0, 15, 0],
    fontSize: 11,
    fontColor: '#B3B3B3',
    legend: {
        show: false
    },
    xAxis: {
        fontSize: 11,
        fontColor: '#B3B3B3'
    },
    yAxis: {
        gridColor: '#E4E4E6'
    },
    extra: {
        column: {
            width: 14
        }
    }
};

const chartsData1 = ref({
    categories: [],
    series: [
        {
            data: []
        }
    ]
});
const chartsData2 = ref({
    categories: [],
    series: [
        {
            data: []
        }
    ]
});

onShow(async () => {
    // #ifdef APP
    const userInfo = uni.getStorageSync('userLoginInfo') ? JSON.parse(uni.getStorageSync('userLoginInfo')) : null;
    if (!userInfo || !userInfo.access_token) {
        return;
    }
    let platform = uni.getSystemInfoSync().platform;
    if (platform == 'android') {
        // 跳转安卓应用市场
        // let appurl = "market://details?id=安卓包的包名"
        //这个是通用应用市场，如果想指定某个应用商店，需要单独查这个应用商店的包名或scheme及参数
        // plus.runtime.openURL(appurl)
        checkAppVersion();
    } else if (platform == 'ios') {
        // const appleId = 对应的ios包的Appleid（不是appid）
        // plus.runtime.launchApplication({
        // 	action: `itms-apps://itunes.apple.com/cn/app/id${appleId}`,
        // })
    }

    // #endif
    if (uni.getStorageSync('userLoginInfo')) {
        await getUserInfo();
        // ios审核 推广内容显示隐藏
        if (uni.getSystemInfoSync().platform === 'ios') {
            commonApis.getIosShowHideFlag().then((res) => {
                uni.setStorageSync('isPromotionShow', !!+res.data[0].value);
            });
        } else {
            uni.setStorageSync('isPromotionShow', true);
        }
    }
    if (userInfomation.value?.identityType == 0) {
        // 地推数据
        getData_DT();
    } else if (userInfomation.value?.identityType == 1) {
        // 管家数据
        getData_GJ();
        getGroupNum();
        getAgencyPayment();
    } else if (userInfomation.value?.identityType == 2) {
        // 运营中心数据
        getData_YY();
        getGroupNum();
        getAgencyPayment();
    } else if (userInfomation.value?.identityType == 4) {
        // 省代数据
        getData_SD();
    }
});
const progressPopup = ref();
const downloadProgress = ref(0);
const checkAppVersion = async () => {
    let appVersion = await new Promise((resolve) => {
        plus.runtime.getProperty(plus.runtime.appid, (appInfo) => {
            console.log(appInfo.versionCode);
            resolve(appInfo.versionCode);
        });
    });

    let AppVersion = await commonApis.getAppVersion();
    console.log(appVersion, AppVersion);
    if (appVersion < AppVersion.data.version) {
        if (AppVersion.data.updateStatus == 0) {
            uni.showModal({
                title: '发现新版本',
                content: '检测到有新版本需要更新，更多全新功能即将为您呈现。',
                showCancel: false,
                confirmText: '马上更新',
                success(res) {
                    if (res.confirm) {
                        progressPopup.value.open();

                        let downloadTask = uni.downloadFile({
                            //执行下载
                            url: AppVersion.data.url, //下载地址
                            success: (downloadResult) => {
                                //下载成功
                                if (downloadResult.statusCode == 200) {
                                    uni.showModal({
                                        title: '',
                                        content: '下载成功，马上安装',
                                        confirmText: '安装',
                                        showCancel: false,
                                        confirmColor: '#2c73ff',
                                        success: function (res) {
                                            if (res.confirm == true) {
                                                if (uni.getStorageSync('appUploadInfo')) {
                                                    uni.removeStorageSync('appUploadInfo');
                                                }

                                                plus.runtime.install(
                                                    //安装
                                                    downloadResult.tempFilePath,
                                                    {
                                                        force: false
                                                    },
                                                    function (res) {
                                                        uni.showToast({
                                                            icon: 'none',
                                                            title: '更新成功，重启中'
                                                        });
                                                        plus.runtime.restart();
                                                    }
                                                );
                                            }
                                        }
                                    });
                                }
                            }
                        });

                        downloadTask.onProgressUpdate((result) => {
                            downloadProgress.value = result.progress;

                            if (result.progress == 100) {
                                downloadProgress.value = 0;
                                progressPopup.value.close();
                            }
                        });
                    }
                }
            });
        } else {
            if (uni.getStorageSync('appUploadInfo')) {
                let appUploadInfo = uni.getStorageSync('appUploadInfo');

                if (AppVersion.data.version === appUploadInfo.version) {
                    if (appUploadInfo.unUpdateFlag) return;
                } else {
                    if (uni.getStorageSync('appUploadInfo')) {
                        uni.removeStorageSync('appUploadInfo');
                    }
                }
            }

            uni.showModal({
                title: '发现新版本',
                content: '检测到有新版本需要更新，更多全新功能即将为您呈现。',
                cancelText: '暂不更新',
                confirmText: '马上更新',
                success(res) {
                    if (res.cancel) {
                        uni.setStorageSync('appUploadInfo', {
                            version: AppVersion.data.version,
                            unUpdateFlag: true
                        });
                    }

                    if (res.confirm) {
                        progressPopup.value.open();
                        let downloadTask = uni.downloadFile({
                            //执行下载
                            url: AppVersion.data.url, //下载地址
                            success: (downloadResult) => {
                                //下载成功
                                if (downloadResult.statusCode == 200) {
                                    uni.showModal({
                                        title: '',
                                        content: '下载成功，马上安装',
                                        confirmText: '安装',
                                        showCancel: false,
                                        confirmColor: '#2c73ff',
                                        success: function (res) {
                                            if (res.confirm == true) {
                                                if (uni.getStorageSync('appUploadInfo')) {
                                                    uni.removeStorageSync('appUploadInfo');
                                                }

                                                plus.runtime.install(
                                                    //安装
                                                    downloadResult.tempFilePath,
                                                    {
                                                        force: false
                                                    },
                                                    function (res) {
                                                        uni.showToast({
                                                            icon: 'none',
                                                            title: '更新成功，重启中'
                                                        });
                                                        plus.runtime.restart();
                                                    }
                                                );
                                            }
                                        }
                                    });
                                }
                            }
                        });

                        downloadTask.onProgressUpdate((result) => {
                            downloadProgress.value = result.progress;
                            if (result.progress == 100) {
                                downloadProgress.value = 0;
                                progressPopup.value.close();
                            }
                        });
                    }
                }
            });
        }
    }
};

let userInfomation = ref(null);
const getUserInfo = async () => {
    await getUserInfoMethod();
    userInfomation.value = JSON.parse(uni.getStorageSync('userInfomation'));
    userRole.value = userInfomation.value.identityType;
};

// 获取团队人数  管家 运营中心
const groupNum = ref(0);
const getGroupNum = async () => {
    let res = await homeApis.getTeamNum();
    groupNum.value = res.data.globBaseNum - res.data.teamNum;
};
// 获取缴费情况  管家 运营中心
const unpaidAgencyFees = ref(0);
const getAgencyPayment = async () => {
    let res = await homeApis.getAgencyPayment();
    unpaidAgencyFees.value = res.data.agentAmount - res.data.payAmount;
};

// 获取地推的数据
const TodayIncome = ref([]);
const getData_DT = async () => {
    let r1 = await homeApis.getTodayIncome_DT();
    let r2 = await homeApis.getPeopleNum_DT();
    let r3 = await homeApis.getBrokerage_DT();

    TodayIncome.value = [+r1.data.todayEarnings, +r1.data.promoterNum, +r1.data.todayCbt, +r1.data.totalReward, +r1.data.totalPromoterNum, +r1.data.cbtBalance.toFixed(2)];

    let categories1 = [];
    let series1 = [];
    let categories2 = [];
    let series2 = [];
    for (let s of r2.data) {
        categories1.push(s.date.substring(5));
        series1.push(s.num);
    }

    for (let s of r3.data) {
        categories2.push(s.date.substring(5));
        series2.push(s.amount);
    }

    chartsData1.value.categories = categories1;
    chartsData1.value.series[0].data = series1;

    chartsData2.value.categories = categories2;
    chartsData2.value.series[0].data = series2;
};
// 获取管家的数据
const getData_GJ = async () => {
    let [r1, r2, r3] = await Promise.all([homeApis.getTodayIncome_GJ(), homeApis.getBrokerage_GJ(), homeApis.getRecommended_GJ()]);

    TodayIncome.value = [
        +r1.data.todayEarnings,
        +r1.data.areaTodayEarnings,
        +r1.data.subAreaChargePersonNum,
        +r1.data.totalEarnings,
        +r1.data.areaTotalRevenue,
        +r1.data.recommendPersonNum
    ];

    let categories1 = [];
    let series1 = [];
    let categories2 = [];
    let series2 = [];
    for (let s of r2.data) {
        categories1.push(s.date.substring(5));
        series1.push(s.num);
    }

    for (let s of r3.data) {
        categories2.push(s.date.substring(5));
        series2.push(s.amount);
    }

    chartsData1.value.categories = categories1;
    chartsData1.value.series[0].data = series1;

    chartsData2.value.categories = categories2;
    chartsData2.value.series[0].data = series2;
};
// 获取运营中心的数据
const getData_YY = async () => {
    let [r1, r2, r3] = await Promise.all([homeApis.getTodayIncome_YY(), homeApis.getBrokerage_YY(), homeApis.getRecommended_YY()]);

    TodayIncome.value = [
        +r1.data.todayEarnings,
        +r1.data.areaTodayEarnings,
        +r1.data.subAreaChargePersonNum,
        +r1.data.totalEarnings,
        +r1.data.areaTotalRevenue,
        +r1.data.recommendPersonNum
    ];

    let categories1 = [];
    let series1 = [];
    let categories2 = [];
    let series2 = [];
    for (let s of r2.data) {
        categories1.push(s.date.substring(5));
        series1.push(s.num);
    }

    for (let s of r3.data) {
        categories2.push(s.date.substring(5));
        series2.push(s.amount);
    }

    chartsData1.value.categories = categories1;
    chartsData1.value.series[0].data = series1;

    chartsData2.value.categories = categories2;
    chartsData2.value.series[0].data = series2;
};
// 获取省代的数据
const getData_SD = async () => {
    let [r1, r2, r3] = await Promise.all([homeApis.getTodayIncome_SD(), homeApis.getBrokerage_SD(), homeApis.getRecommended_SD()]);
    TodayIncome.value = [+r1.data.todayEarnings, +r1.data.operationChargePersonNum, +r1.data.stewardChargePersonNum];

    let categories1 = [];
    let series1 = [];
    let categories2 = [];
    let series2 = [];
    for (let s of r2.data) {
        categories1.push(s.date.substring(5));
        series1.push(s.num);
    }

    for (let s of r3.data) {
        categories2.push(s.date.substring(5));
        series2.push(s.amount);
    }

    chartsData1.value.categories = categories1;
    chartsData1.value.series[0].data = series1;

    chartsData2.value.categories = categories2;
    chartsData2.value.series[0].data = series2;
};

const userDataBoardText = [
    ['今日奖励(元)', '今日新增人数', '今日CBT收入', '总奖励(元)', '总人数', '积分(CBT)余额'],
    ['今日奖励(元)', '今日区域交易GMV', '用户数量', '总奖励(元)', '总区域交易GMV', '邀请管家数'],
    ['今日奖励', '今日区域交易GMV', '管家数量', '总奖励', '区域总交易GMV', '邀请运营中心数'],
    [],
    ['今日收益', '运营数量', '管家数量']
];

const userCards = computed(() => {
    let cards = [
        {
            title: '订单管理',
            desc: '快捷查看',
            icon: '/static/home/card_icon1.png',
            pagePath: '/pages_home/orderManage/orderManage'
        },
        {
            title: '奖励中心',
            desc: '奖励规则',
            icon: '/static/home/card_icon2.png',
            pagePath: '/pages_home/rewardCenter/rewardCenter'
        },
        {
            title: '帮手管理',
            desc: '快速调度',
            icon: '/static/home/card_icon3.png',
            pagePath: '/pages_home/helperManage/helperManage'
        },
        {
            title: '管家管理',
            desc: '深度运营',
            icon: '/static/home/card_icon4.png',
            pagePath: '/pages_home/butlerManage/butlerManage'
        },
        {
            title: '用户转积分',
            desc: '转来积分',
            icon: '/static/home/card_icon5.png',
            pagePath: '/pages_home/userRewards/userRewards'
        },
        {
            title: '我的二维码',
            desc: '我的二维码',
            icon: '/static/home/card_icon6.png',
            pagePath: '/pages_home/promotionQRcode/promotionQRcode'
        }
    ];

    let res = [];

    switch (+userRole.value) {
        case 0:
            res = cards.slice(4);
            break;
        case 1:
            res = cards.slice(0, 2);
            break;
        case 2:
            res = cards.slice(0, 4);
            break;
    }
    return res;
});

const cardClick = (item) => {
    uni.navigateTo({
        url: item.pagePath
    });
};

// 代理费是否交齐
const goAgencyFeePay = () => {
    uni.navigateTo({
        url: '/pages_finance/agencyFeePay/agencyFeePay'
    });
};

const dataBoardItemClick = (index) => {
    /**
     * 角色0 推客   num 5  推广用户列表
     * 角色1 管家   num 3  所管小区用户列表  6 邀请管家列表
     * 角色2 运营   num 3  所管区域管家列表  6 邀请运营列表
     *
     * 角色4 省代   num 2  所管区域运营列表  3 所管区域管家列表
     */

    if (userRole.value == 0 && index != 5) {
        return;
    }
    if (userRole.value == 1 && index != 3 && index != 6) {
        return;
    }
    if (userRole.value == 2 && index != 3 && index != 6) {
        return;
    }
    if (userRole.value == 4 && index != 2 && index != 3) {
        return;
    }

    if ((userRole.value == 2 || userRole.value == 4) && index == 3) {
        uni.navigateTo({
            url: '/pages_home/butlerManage/butlerManage'
        });
        return;
    }

    uni.navigateTo({
        url: '/pages_user/dataBoardList/dataBoardList?num=' + index
    });
};
</script>
<style lang="scss">
page {
    background: linear-gradient(60deg, #e8f6ff 0%, #f2f3f5 100%);
}
</style>

<style lang="scss" scoped>
.page {
    padding: 0 24rpx 32rpx;
}

.topBox {
    padding: 30rpx 0;
}

.target {
    margin-bottom: 24rpx;
    width: 100%;
    height: 80rpx;
    background: #ffffff;
    border-radius: 16rpx;
    padding: 0 24rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    image {
        width: 40rpx;
        height: 40rpx;
    }

    .text {
        margin-left: 44rpx;
        flex: 1;
        font-size: 24rpx;
        color: #333333;
    }
}

.dataBoard {
    position: sticky;
    top: var(--status-bar-height);
    z-index: 5;
    width: 100%;
    height: auto;
    background: #2c72ff;
    border-radius: 16rpx;
    margin-bottom: 24rpx;
    display: flex;
    align-items: center;
    gap: 20rpx 3%;
    flex-wrap: wrap;
    padding: 20rpx;

    .item {
        margin-right: 2%;
        margin-bottom: 20rpx;
        min-width: 30%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        &:nth-child(3n) {
            margin-right: 0;
        }

        &:nth-child(n + 4) {
            margin-bottom: 0;
        }

        .value {
            font-weight: bold;
            font-size: 40rpx;
            color: #ffffff;
            text-align: center;
            margin-bottom: 4rpx;
        }
        .label {
            font-size: 24rpx;
            color: rgba(255, 255, 255, 0.7);
            text-align: center;
        }
    }
}

.agencyFeeRemind {
    // position: sticky;
    // top: var(--status-bar-height);
    // z-index: 5;

    width: 100%;
    height: 80rpx;
    background: #ffffff;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24rpx;
    padding-left: 42rpx;
    padding-right: 26rpx;
    span {
        font-size: 24rpx;
        color: #333333;
    }
    image {
        width: 26rpx;
        height: 26rpx;
    }
}

.cards {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    gap: 22rpx;
    margin-bottom: 24rpx;

    .card {
        width: calc(50% - 11rpx);
        height: auto;
        background: #ffffff;
        border-radius: 16rpx;
        position: relative;
        padding: 24rpx 28rpx 20rpx;
        .title {
            font-size: 36rpx;
            color: #333333;
            line-height: 50rpx;
        }
        .desc {
            margin-top: 8rpx;
            font-size: 22rpx;
            color: #999999;
            line-height: 32rpx;
        }
        image {
            margin-top: 14rpx;
            width: 26rpx;
            height: 26rpx;
        }
        .icon {
            position: absolute;
            right: 24rpx;
            bottom: 20rpx;
            width: 68rpx;
            height: 68rpx;
        }
    }
}

.charts {
    .item {
        width: 100%;
        height: auto;
        background: #ffffff;
        border-radius: 16rpx;
        margin-bottom: 24rpx;
        padding: 24rpx 32rpx;
        .title {
            font-size: 28rpx;
            color: #333333;
            span {
                font-size: 22rpx;
                color: #999999;
                margin-left: 24rpx;
            }
        }
        .charts-box {
            margin-top: 20rpx;
            height: 240rpx;
            width: 100%;
        }
    }
}

.progressPopupContent {
    width: 80vw;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx 24rpx;
    box-shadow: 0 0 40rpx 10rpx rgba(44, 114, 255, 0.2);

    .title {
        text-align: center;
        font-size: 34rpx;
        font-weight: bold;
        color: #333333;
        margin-bottom: 16rpx;
    }
    .progressBox {
        width: 100%;
        position: relative;
        .progress {
            width: 100%;
            background-color: #ebebeb;
            border-radius: 8rpx;
            height: 10rpx;
        }
        .progress_a {
            z-index: 5;
            position: absolute;
            top: 0;
            left: 0;
            border-radius: 8rpx;
            height: 10rpx;
            background-color: #2c73ff;
        }

        .progress_text {
            margin-top: 20rpx;
            font-size: 28rpx;
            color: #333333;
            text-align: center;
        }
    }
}
</style>
